package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.dao.SysUserAdMapper;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIAdminUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserProfitService userProfitService;
    @Autowired
    private WalletCompanyService walletCompanyService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private UserRewardService userRewardService;
    @Autowired
    private RelationsService relationsService;
    @Autowired
    private UserOnlineService userOnlineService;
    @Autowired
    private QRCodeRecordService qrCodeRecordService;

    /**
     * @api {get} /api/admin/users 后台管理-会员管理-会员列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/users
     *
     * @apiName findSysUserPage
     * @apiGroup SysUser
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                       "ctime": 1504439519742,
     *                       "department": "",
     *                       "email": "",
     *                       "headimgurl": "http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIJicaiaxiaACsY7SicvpETezMPppZJNKdR1vZHpKkoIvgqRGAOfuJE5t1vCaic44Jc8LoBhAdmOpkeeBg/0",
     *                       "id": 63283,
     *                       "idCard": "",
     *                       "lastIp": "124.133.150.99",
     *                       "lastTime": 1504596697368,
     *                       "locked": false,
     *                       "mtime": 1504439519742,
     *                       "nickname": "过去那些过不去的",
     *                       "password": "$2a$10$ck29aWiGaaBHkgnrekOxUe9ib5zw/4MggineGk8okoiaQm9dT.NzO",
     *                       "phone": "13011714281",
     *                       "position": "",
     *                       "qrimgurl": "http://static.ruitaowang.com/qr/qr_63283.png",
     *                       "realName": "",
     *                       "remark": "",
     *                       "rstatus": 0,
     *                       "userType": 0,
     *                       "username": "13011714281"
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/users"
     *  }
     */

    @RequestMapping(value = "/api/admin/users")
    public String findSysUserPage(SysUser address, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        address.setPage(page);
        address.setOrderBy("id desc");
        List<SysUser> sysUsers = sysUserService.searchForPage(address);
        MsgOut o = MsgOut.success(sysUsers);
        o.setRecords(address.getRecords());
        o.setTotal(address.getTotal());
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/admin/stat/userAll")
    public String countUserAll(){
        SysUser sysUser = new SysUser();
        Long userAll=sysUserService.userCount(sysUser);
        MsgOut o = MsgOut.success(userAll);
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/admin/day/dayData")
    public String countDayData(Long stime,Long etime){
        Long dataAll=sysUserService.countDayData(stime,etime);
        Long dayAll=sysUserService.countDayAll(etime);
        HashMap<String,Long> map = new HashMap<String,Long>();
        map.put("dataAll",dataAll);
        map.put("dayAll",dayAll);
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }
    /**
     * @apiName findSysUserPage
     * @apiGroup SysUser
     *
     * @apiParam {int} userId 用户ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                       "ctime": 1504439519742,
     *                       "department": "",
     *                       "email": "",
     *                       "headimgurl": "http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIJicaiaxiaACsY7SicvpETezMPppZJNKdR1vZHpKkoIvgqRGAOfuJE5t1vCaic44Jc8LoBhAdmOpkeeBg/0",
     *                       "id": 63283,
     *                       "idCard": "",
     *                       "lastIp": "124.133.150.99",
     *                       "lastTime": 1504596697368,
     *                       "locked": false,
     *                       "mtime": 1504439519742,
     *                       "nickname": "过去那些过不去的",
     *                       "password": "$2a$10$ck29aWiGaaBHkgnrekOxUe9ib5zw/4MggineGk8okoiaQm9dT.NzO",
     *                       "phone": "13011714281",
     *                       "position": "",
     *                       "qrimgurl": "http://static.ruitaowang.com/qr/qr_63283.png",
     *                       "realName": "",
     *                       "remark": "",
     *                       "rstatus": 0,
     *                       "userType": 0,
     *                       "username": "13011714281"
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/users/ByPK"
     *  }
     */

    @RequestMapping(value = "/api/admin/users/ByPK")
    public String findSysUserByPK(Long userId) {
        MsgOut o = MsgOut.success(sysUserService.selectByPK(userId));
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/admin/user/parent")
    public String findSysUserParent(Long uesrId) {
        List<SysUser> sysUsers=new ArrayList<>();
        List<Long> userIds=relationsService.selectAllParents(uesrId);
        for (Long id:userIds){
            sysUsers.add(sysUserService.selectByPK(id));
        }
        MsgOut o = MsgOut.success(sysUsers);
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/wap/user/update", method = RequestMethod.PUT)
    public String wapUpdateUser(SysUser address) {
        sysUserService.update(address);
        MsgOut o = MsgOut.success(address);
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/wap/user/online")
    public String findUserOnline(UserOnline userOnline, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(userOnline)){
            return this.renderJson(MsgOut.error("參數錯誤"));
        }
        userOnline.setPage(page);
        MsgOut o = MsgOut.success(userOnlineService.selectForPage(userOnline));
        o.setRecords(userOnline.getRecords());
        o.setTotal(userOnline.getTotal());
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/wap/qrCodeRecord")
    public String findUserOnline(QRCodeRecord qrCodeRecord,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser sysUser=sysUserService.selectByPK(Long.parseLong(userId));
        qrCodeRecord.setUserId(sysUser.getId());
        List<QRCodeRecord>qrCodeRecords=qrCodeRecordService.select(qrCodeRecord);
        if (ObjectUtils.isEmpty(qrCodeRecords)){
            QRCodeRecord qrCode=new QRCodeRecord();
            qrCode.setUserId(Long.parseLong(userId));
            qrCodeRecordService.insert(qrCodeRecord);
        }else {
            qrCodeRecord =qrCodeRecords.get(0);
        }
        MsgOut o = MsgOut.success(qrCodeRecord);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/admin/user/count")
    public String userCount(SysUser sysUser){
        Map map = new HashMap();
        Long userCount = sysUserService.userCount(sysUser);
        map.put("userCount",userCount);
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }
}


